<template>
    <div class="switch-renderer">
        <el-switch
            v-if="field.prop"
            @change="onChange"
            :model-value="cellValue"
            :loading="loading"
            :active-value="field.custom.active || '1'"
            :inactive-value="field.custom.inactive || '0'"
            v-bind="invokeTableContextDataFun(field.customRenderAttr?.switch, { row, field, cellValue, column, index })"
        />
    </div>
</template>

<script setup lang="ts">
import { TableColumnCtx } from 'element-plus'
import { inject, ref } from 'vue'
import { getCellValue, invokeTableContextDataFun } from '/@/components/table/index'
import type baTableClass from '/@/utils/baTable'

interface Props {
    row: TableRow
    field: TableColumn
    column: TableColumnCtx<TableRow>
    index: number
}

const loading = ref(false)
const isInitialRender = ref(true)
const props = defineProps<Props>()
const baTable = inject('baTable') as baTableClass
const cellValue = ref(getCellValue(props.row, props.field, props.column, props.index))

if (typeof cellValue.value === 'number') {
    cellValue.value = cellValue.value.toString()
}

const onChange = (value: string | number | boolean) => {
    // 初始化渲染时不调用API
    if (isInitialRender.value) {
        isInitialRender.value = false
        baTable.onTableAction('field-change', { value: value, ...props })
        return
    }

    // 用户点击切换状态时调用API
    const pk = baTable.table.pk!
    const originalValue = cellValue.value

    loading.value = true
    const data = {
        ...props.row,
        [pk]: props.row[pk],
        [props.field.prop!]: value,
    }
    baTable.api
        .postData('edit', data)
        .then(() => {
            cellValue.value = value
            baTable.onTableAction('field-change', { value: value, ...props })
        })
        .catch((e: Error) => {
            console.error('switch postData error:', e)
            // 出错时恢复原状态
            cellValue.value = originalValue
        })
        .finally(() => {
            loading.value = false
        })
}

// 组件挂载后标记初始化完成
setTimeout(() => {
    isInitialRender.value = false
}, 0)
</script>

<style scoped>
.switch-renderer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
